<script setup>
import {ref} from 'vue';
import {getRolePickApi} from '@/service/auth.js';
import {getUserRoleApi,setUserRoleApi} from '@/service/user.js';
import {ElMessage} from "element-plus";

const emits = defineEmits(['reload']);
const reload = () => {
  emits('reload');
};

const visible = ref(false);

// 设置表单数据
const ruleForm = ref({
  user_id: 0,
  role: []
});

// 表单验证规则
const rules = ref({
  role: [
    {required: true, message: '请选择角色', trigger: 'change'}
  ]
});

// 角色列表
const roleList = ref([]);

// 获取角色列表
const fetchRoleList = () => {
  getRolePickApi().then(res => {
    roleList.value = res.data;
  });
};

// 获取用户角色
const fetchUserRole = (user_id) => {
  getUserRoleApi({user_id}).then(res => {
    ruleForm.value.role = res.data;
  });
};



// 打开抽屉
const openDrawer = (user_id) => {
  visible.value = true;
  ruleForm.value.user_id = user_id;
  fetchRoleList();
  fetchUserRole(user_id);
};

// 关闭抽屉
const closeDrawer = () => {
  visible.value = false;
  // 重置表单
  ruleForm.value = {
    user_id: 0,
    role: []
  };
};

// 保存
const ruleFormRef = ref(null);
const handleSave = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      setUserRoleApi(ruleForm.value).then(res => {
        if (res.code !== 200) {
          return ElMessage.error(res.msg);
        } else {
          ElMessage.success(res.msg);
          closeDrawer();
          reload();
        }
      });
    }
  });
};

defineExpose({
  openDrawer
});

</script>

<template>
  <el-drawer v-model="visible" size="30%" title="用户授权" :close-on-click-modal="false">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" label-position="top">
      <el-form-item label="角色">
        <el-checkbox-group v-model="ruleForm.role">
          <el-checkbox v-for="item in roleList" :key="item.id" :value="item.id">{{item.title}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="closeDrawer">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>

</style>